package io.renren.modules.mvs.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.renren.common.annotation.SysLog;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.R;
import io.renren.modules.mvs.entity.VehicleEntity;
import io.renren.modules.mvs.entity.ViolationEntity;
import io.renren.modules.mvs.service.VehicleService;
import io.renren.modules.mvs.service.ViolationService;
import io.renren.modules.sys.entity.SysDictEntity;
import io.renren.modules.sys.service.impl.SysDictServiceImpl;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static io.renren.common.utils.Constant.*;


/**
 * 机动车表
 *
 * @author chenshun
 * @email sunlightcs@gmail.com
 * @date 2025-03-30 17:08:24
 */
@RestController
@RequestMapping("mvs/vehicle")
public class VehicleController {
    @Autowired
    private VehicleService vehicleService;
    @Autowired
    private ViolationService violationService;
    @Autowired
    private SysDictServiceImpl sysDictService;

    /**
     * 列表
     */
    @GetMapping("/list")
    @RequiresPermissions("mvs:vehicle:list")
    public R list(@RequestParam Map<String, Object> params) {
        PageUtils page = vehicleService.queryPage(params);

        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @GetMapping("/info/{id}")
    @RequiresPermissions("mvs:vehicle:info")
    public R info(@PathVariable("id") Integer id) {
        VehicleEntity vehicle = vehicleService.getById(id);

        return R.ok().put("vehicle", vehicle);
    }

    /**
     * 保存
     */
    @SysLog("新增机动车")
    @PostMapping("/save")
    @RequiresPermissions("mvs:vehicle:save")
    public R save(@RequestBody VehicleEntity vehicle) {
        if (!checkVehicleInfo(vehicle)) {
            return R.error("机动车信息的格式错误");
        }
        vehicleService.save(vehicle);
        return R.ok();
    }

    private boolean checkVehicleInfo(VehicleEntity vehicle) {
        // 检查车牌号和车架号的格式
        if (!vehicle.getPlateNumber().matches(PLATE_NUMBER_REGEX) || !vehicle.getVin().matches(VIN_REGEX)) {
            return false;
        }
        // 检查机动车颜色、品牌和类型是否在字典表中存在
        Integer count = sysDictService.lambdaQuery()
                .in(SysDictEntity::getCode, Arrays.asList(vehicle.getVehicleColor(), vehicle.getVehicleBrand(), vehicle.getVehicleType()))
                .count();
        return count == 3;
    }

    /**
     * 修改
     */
    @SysLog("修改机动车")
    @PutMapping("/update")
    @RequiresPermissions("mvs:vehicle:update")
    public R update(@RequestBody VehicleEntity vehicle) {
        if (!checkVehicleInfo(vehicle)) {
            return R.error("机动车信息的格式错误");
        }

        vehicleService.updateById(vehicle);
        return R.ok();
    }

    /**
     * 删除
     */
    @SysLog("删除机动车")
    @DeleteMapping("/delete")
    @RequiresPermissions("mvs:vehicle:delete")
    public R delete(@RequestBody Integer[] ids) {
        // 检查被删除机动车下有没有违章记录
        int count = violationService.count(new LambdaQueryWrapper<ViolationEntity>()
                .in(ViolationEntity::getVehicleId, Arrays.asList(ids)));
        if (count > 0) {
            return R.error("被删除机动车下存在违章记录，不能删除");
        }

        vehicleService.removeByIds(Arrays.asList(ids));
        return R.ok();
    }

    /**
     * 获取指定用户下机动车的车牌号列表
     */
    @GetMapping("/list/plateNumber")
    @RequiresPermissions("mvs:vehicle:list")
    public R plateNumberListByUserId(@RequestParam(defaultValue = "0") Integer userId) {
        List<VehicleEntity> list = vehicleService.getPlateNumberListByUserId(userId);
        return R.ok().put("vehicleList", list);
    }

    /**
     * 根据关键字查询车牌号（默认只返回10条）
     */
    @GetMapping("/list/query")
    @RequiresPermissions("mvs:vehicle:list")
    public R plateNumberListByKey(@RequestParam(required = false) String key, @RequestParam(defaultValue = "10") int limit) {
        List<VehicleEntity> list = vehicleService.getPlateNumberListByKey(key, limit);
        return R.ok().put("vehicleList", list);
    }
}
